package auth

import (
	"fmt"
	"gin_demo/utils"
	"github.com/gin-gonic/gin"
	"net/http"
)

func (*UserAuth) AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("Authorization")

		// 如果 token 为空，则拒绝请求

		username, err := utils.Jwt.VerifyToken(token)
		if err != nil {
			fmt.Errorf("token: %s\n", token)
			c.JSON(http.StatusUnauthorized, gin.H{
				"error": "Unauthorized",
			})
			c.Abort()
			return
		}
		c.AddParam("username", username)
		// 如果 token 正确，则继续处理请求
		c.Next()
	}
}
